﻿CREATE FUNCTION [dbo].[CalcTax]
(
	@TaxRateID int,
	@BaseAmount money
)
RETURNS money
AS
BEGIN
	declare @tax money
	declare @TaxZone nvarchar(50)
	declare @TaxRate decimal(6, 4)

	select @TaxZone = T2.Name, @TaxRate = T1.Rate
	from tblTaxRate T1
		join tblTaxZone T2 on T1.TaxZoneID = T2.TaxZoneID

	if @TaxZone = 'Maine'
		set @tax = (FLOOR(@BaseAmount) * @TaxRate) +
			case when @BaseAmount - FLOOR(@BaseAmount) < .1 then 0 
				else ceiling((@BaseAmount - FLOOR(@BaseAmount)) * 100 * @TaxRate) / 100 end
	else
		set @tax = FLOOR(@BaseAmount * @TaxRate * 100) / 100

	return @tax
END